package com.merelyb.task.handle.affpay;

import com.merelyb.data.service.service.mybatis.bean.affpay.AffpayCommission;
import com.merelyb.data.service.service.mybatis.bean.affpay.AffpayInfo;
import com.merelyb.data.service.service.mybatis.bean.affpay.AffpayPaymentFrequency;
import com.merelyb.data.service.service.mybatis.bean.affpay.AffpayPaymethod;
import com.merelyb.data.service.service.service.affpay.AffpayCommissionService;
import com.merelyb.data.service.service.service.affpay.AffpayInfoService;
import com.merelyb.data.service.service.service.affpay.AffpayPaymentFrequencyService;
import com.merelyb.data.service.service.service.affpay.AffpayPaymethodService;
import com.merelyb.util.FileUtil;
import com.merelyb.util.HttpClientUtil;
import com.merelyb.util.StringCodeUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by LiM on 2017/12/15.
 */
@Service
public class AffpayGetHandler {

    @Autowired
    AffpayInfoService affpayInfoService;
    @Autowired
    AffpayPaymentFrequencyService affpayPaymentFrequencyService;
    @Autowired
    AffpayPaymethodService affpayPaymethodService;
    @Autowired
    AffpayCommissionService affpayCommissionService;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");

    private String sHost = "http://www.affpaying.com/";
    private List<String> urlList;
    private Log affPayLog = LogFactory.getLog(this.getClass());


    /**
     * 解析页面地址
     *
     * @param sHtml
     */
    private void parseUrlInfo(String sHtml) {
        Document document = Jsoup.parse(sHtml);
        Elements elements = document.getElementsByAttributeValue("class", "title-right");
        if (elements != null && elements.size() > 0) {
            for (Element eleDiv : elements
                    ) {
                Elements eleDivImgs = eleDiv.parent().getElementsByClass("thumb");
                if (eleDivImgs != null && eleDivImgs.size() > 0) {
                    Elements eleImgs = eleDivImgs.get(0).children();
                    if (eleImgs != null && eleImgs.size() > 0) {
                        for (Element eleImg : eleImgs) {
                            if (!eleImg.tag().getName().equals("a")) continue;
                            String sUrl = eleImg.attr("href");
                            if (eleImg.children() != null) {
                                sUrl = sUrl + "&&&&&&" + eleImg.children().get(0).getElementsByTag("img").get(0).attr("src");
                            }
                            urlList.add(sUrl);
                        }
                    }
                } else {
                    Elements eleDivImgOthers = eleDiv.parent().parent().getElementsByClass("thumb");
                    if (eleDivImgOthers != null && eleDivImgOthers.size() > 0) {
                        Elements eleImgs = eleDivImgOthers.get(0).children();
                        if (eleImgs != null && eleImgs.size() > 0) {
                            for (Element eleImg : eleImgs) {
                                if (!eleImg.tag().getName().equals("a")) continue;
                                String sUrl = eleImg.attr("href");
                                if (eleImg.children() != null) {
                                    sUrl = sUrl + "&&&&&&" + eleImg.children().get(0).getElementsByTag("img").get(0).attr("src");
                                }
                                urlList.add(sUrl);
                            }
                        }
                    }
                }

            }
        }
    }


    /**
     * 获取所有的url页面地址
     */
    private void getAppPayingUrl() {
        urlList = new ArrayList<>();
        affPayLog.info("------------------------开始获取------------------------------------");
        for (int i = 1; i < 77; i++) {
            String sUrl = sHost + "page/" + String.valueOf(i);
            String sResult = HttpClientUtil.httpGetRequest(sUrl);
            JSONObject jsonMap = new JSONObject(sResult);
            JSONObject jsonData = (JSONObject) jsonMap.get("map");
            String sHtml = StringCodeUtils.decodeUnicode(jsonData.getString("data"));
            parseUrlInfo(sHtml);
            affPayLog.info("------------------------共：" + String.valueOf(urlList.size()) + "条------------------------------------");
            for (int j = urlList.size() - 1; j > -1; j--) {
                try {
                    affPayLog.info("------------------------解析：" + urlList.get(j) + "------------------------------------");
                    String[] sInfo = urlList.get(j).split("&&&&&&");
                    if (sInfo.length > 0)
                        FileUtils.copyURLToFile(new URL(sInfo[1]), new File("/home/phpweb/"
                                + sInfo[1].replace(sHost, "")));
                    getPageInfo(sInfo[0], sInfo.length > 0 ? sInfo[1].replace(sHost, "") : "");
                    affPayLog.info("------------------------解析完成：" + urlList.get(j) + "------------------------------------");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    continue;
                }
            }
            urlList.clear();
        }
        affPayLog.info("------------------------获取结束------------------------------------");
    }

    /**
     * 获取页面信息
     *
     * @param sUrl
     */
    private void getPageInfo(String sUrl, String sImage) throws Exception {
        String sResult = HttpClientUtil.httpGetRequest(sUrl);
        JSONObject jsonMap = new JSONObject(sResult);
        JSONObject jsonData = (JSONObject) jsonMap.get("map");
        if (jsonData.has("data")) {
            String sHtml = StringCodeUtils.decodeUnicode(jsonData.getString("data"));
            parsePageInfo(sHtml, sImage);
        }
    }

    /**
     * 解析页面详细信息
     *
     * @param sHtml
     * @throws Exception
     */
    private void parsePageInfo(String sHtml, String sImage) throws Exception {
        Document document = Jsoup.parse(sHtml);
        AffpayInfo affpayInfo = new AffpayInfo();
        affpayInfo.setImgUrl(sImage);
        affpayInfo.setCreateTime(new Date());
        affpayInfo.setIsDelete(0);
        Element eleHeader = document.getElementById("s_single_img_right");
        if (eleHeader != null) {
            Elements eleHeaderChilds = eleHeader.children();
            if (eleHeaderChilds != null && eleHeaderChilds.size() > 0) {
                affpayInfo.setId(Long.parseLong(simpleDateFormat.format(new Date())));
                for (Element eleHea : eleHeaderChilds
                        ) {
                    if (!(eleHea.tag().getName().equals("h1") || eleHea.tag().getName().equals("div"))) continue;
                    if (eleHea.tag().getName().equals("h1")) {
                        affpayInfo.setAffpayName(eleHea.text().trim());
                    }
                    if (eleHea.tag().getName().equals("div")) {
                        if (eleHea.outerHtml().contains("s_rate_mid") && eleHea.text().contains("/") && eleHea.text().indexOf("/") > -1) {
                            affpayInfo.setStartsNum(Float.parseFloat(eleHea.getElementsByClass("rating").get(0).text()));
                        } else if (eleHea.text().indexOf("Tracking") > -1) {
                            String[] sEval = eleHea.text().trim().replace("Offers:", "").replace("Payout:", ",")
                                    .replace("Tracking:", ",").replace("Support:", ",").split(",");
                            affpayInfo.setOffers(sEval[0].equals("N/A") ? null : Float.parseFloat(sEval[0]));
                            affpayInfo.setPayout(sEval[1].equals("N/A") ? null : Float.parseFloat(sEval[1]));
                            affpayInfo.setTracking(sEval[2].equals("N/A") ? null : Float.parseFloat(sEval[2]));
                            affpayInfo.setSupport(sEval[3].equals("N/A") ? null : Float.parseFloat(sEval[3]));
                        }
                    }
                }
            }
        }
        Element eleUrlContains = document.getElementById("s_single_head_info");
        if (eleUrlContains != null) {
            Elements eleAUrls = eleUrlContains.getElementsByTag("a");
            if (eleAUrls != null && eleAUrls.size() > 0) {
                String sUrl = eleAUrls.get(0).attr("href");
                sUrl = sUrl.substring(0, sUrl.contains("?") ? sUrl.indexOf("?") : sUrl.length());
                affpayInfo.setRegistUrl(sUrl);
            }
        }
        List<AffpayCommission> affpayCommissionList = new ArrayList<>();
        List<AffpayPaymentFrequency> affpayPaymentFrequencyList = new ArrayList<>();
        List<AffpayPaymethod> affpayPaymethodList = new ArrayList<>();
        Element eleInfoContains = document.getElementById("s_network_detail_con");
        if (eleInfoContains != null) {
            Elements eleInfoPs = eleInfoContains.getElementsByTag("p");
            if (eleInfoPs != null && eleInfoPs.size() > 0) {
                for (Element eleInfo : eleInfoPs
                        ) {
                    if (eleInfo.text().indexOf("Number of Offers") > -1) {
                        affpayInfo.setNumberOfOffers(eleInfo.getElementsByTag("span").get(1).text());
                    }
                    if (eleInfo.text().indexOf("Commission Type") > -1) {
                        String sCommission = eleInfo.getElementsByTag("span").get(1).text().trim();
                        affpayInfo.setPayCommission(sCommission);
                        if(sCommission.contains("(")){
                            AffpayCommission affpayCommission = new AffpayCommission();
                            affpayCommission.setAffpayId(affpayInfo.getId());
                            affpayCommission.setCommissionType(sCommission);
                            affpayCommission.setCreateTime(new Date());
                            affpayCommission.setIsDelete(0);
                            affpayCommissionList.add(affpayCommission);
                        }else {
                            String[] sTypes = sCommission.split(",");
                            for (String sTy : sTypes
                                    ) {
                                if(sTy.contains("/")){
                                    String[] sComm = sTy.split("/");
                                    for (String sCommType: sComm
                                         ) {
                                        AffpayCommission affpayCommission = new AffpayCommission();
                                        affpayCommission.setAffpayId(affpayInfo.getId());
                                        affpayCommission.setCommissionType(sCommType);
                                        affpayCommission.setCreateTime(new Date());
                                        affpayCommission.setIsDelete(0);
                                        affpayCommissionList.add(affpayCommission);
                                    }
                                }else {
                                    AffpayCommission affpayCommission = new AffpayCommission();
                                    affpayCommission.setAffpayId(affpayInfo.getId());
                                    affpayCommission.setCommissionType(sTy);
                                    affpayCommission.setCreateTime(new Date());
                                    affpayCommission.setIsDelete(0);
                                    affpayCommissionList.add(affpayCommission);
                                }
                            }
                        }

                    }
                    if (eleInfo.text().indexOf("Minimum Payment") > -1) {
                        affpayInfo.setMinimumPayment(eleInfo.getElementsByTag("span").get(1).text());
                    }
                    if (eleInfo.text().indexOf("Payment Frequency") > -1) {
                        affpayInfo.setPaymentFrequency(eleInfo.text().replace("Payment Frequency", ""));
                        String sFrequency = eleInfo.getElementsByTag("span").get(1).text().trim();
                        if (!sFrequency.contains("(")) {
                            String[] sFreqs = sFrequency.split(",");
                            for (String sFre : sFreqs
                                    ) {
                                if (sFre.contains("/")) {
                                    String[] sPayF = sFre.split("/");
                                    for (String sPY : sPayF
                                            ) {
                                        AffpayPaymentFrequency affpayPaymentFrequency = new AffpayPaymentFrequency();
                                        affpayPaymentFrequency.setAffpayId(affpayInfo.getId());
                                        affpayPaymentFrequency.setPaymentFrequency(sPY);
                                        affpayPaymentFrequency.setCreateTime(new Date());
                                        affpayPaymentFrequency.setIsDelete(0);
                                        affpayPaymentFrequencyList.add(affpayPaymentFrequency);
                                    }
                                } else {
                                    AffpayPaymentFrequency affpayPaymentFrequency = new AffpayPaymentFrequency();
                                    affpayPaymentFrequency.setAffpayId(affpayInfo.getId());
                                    affpayPaymentFrequency.setPaymentFrequency(sFre);
                                    affpayPaymentFrequency.setCreateTime(new Date());
                                    affpayPaymentFrequency.setIsDelete(0);
                                    affpayPaymentFrequencyList.add(affpayPaymentFrequency);
                                }
                            }
                        } else {
                            AffpayPaymentFrequency affpayPaymentFrequency = new AffpayPaymentFrequency();
                            affpayPaymentFrequency.setAffpayId(affpayInfo.getId());
                            affpayPaymentFrequency.setPaymentFrequency(sFrequency);
                            affpayPaymentFrequency.setCreateTime(new Date());
                            affpayPaymentFrequency.setIsDelete(0);
                            affpayPaymentFrequencyList.add(affpayPaymentFrequency);
                        }
                    }
                    if (eleInfo.text().indexOf("Payment Method") > -1) {
                        String[] sMethods = eleInfo.getElementsByTag("span").get(1).text().trim().split(",");
                        for (String sMeth : sMethods
                                ) {
                            if (sMeth.contains("/")) {
                                String[] sOtherMethods = sMeth.split("/");
                                for (String sMd : sOtherMethods
                                        ) {
                                    AffpayPaymethod affpayPaymethod = new AffpayPaymethod();
                                    affpayPaymethod.setAffpayId(affpayInfo.getId());
                                    affpayPaymethod.setPaymethod(sMd.trim());
                                    affpayPaymethod.setCreateTime(new Date());
                                    affpayPaymethod.setIsDelete(0);
                                    affpayPaymethodList.add(affpayPaymethod);
                                }
                            } else {
                                AffpayPaymethod affpayPaymethod = new AffpayPaymethod();
                                affpayPaymethod.setAffpayId(affpayInfo.getId());
                                affpayPaymethod.setPaymethod(sMeth.trim());
                                affpayPaymethod.setCreateTime(new Date());
                                affpayPaymethod.setIsDelete(0);
                                affpayPaymethodList.add(affpayPaymethod);
                            }
                        }
                    }
                    if (eleInfo.text().indexOf("Referral Commission") > -1) {
                        affpayInfo.setReferralCommission(eleInfo.getElementsByTag("span").get(1).text());
                    }
                    if (eleInfo.text().indexOf("Tracking Software") > -1) {
                        affpayInfo.setTrackingSoftware(eleInfo.getElementsByTag("span").get(1).text());
                    }
                    if (eleInfo.text().indexOf("Tracking Link") > -1) {
                        affpayInfo.setTrackingLink(eleInfo.getElementsByTag("span").get(1).text());
                    }
                    if (eleInfo.text().indexOf("Twitter") > -1) {
                        affpayInfo.setTwitterUrl(eleInfo.text());
                    }
                    if (eleInfo.text().indexOf("Facebook") > -1) {
                        affpayInfo.setFacebookUrl(eleInfo.text());
                    }
                    if (eleInfo.text().indexOf("Affiliate Manager") > -1) {
                        affpayInfo.setAffiliateManage(eleInfo.text());
                    }
                }
            }
        }

        if (affpayInfo != null) {
            affpayInfoService.addData(affpayInfo);
            if (affpayCommissionList.size() > 0) {
                affpayCommissionService.addData(affpayCommissionList);
            }
            if (affpayPaymethodList.size() > 0) {
                affpayPaymethodService.addData(affpayPaymethodList);
            }
            if (affpayPaymentFrequencyList.size() > 0) {
                affpayPaymentFrequencyService.addData(affpayPaymentFrequencyList);
            }
        }

    }

    public void syncAffpay() {
        getAppPayingUrl();
    }


}
